<template>
  <div class="fillInTheContract-container">
    <!-- 合同的html -->
    <div :class="[
      rightBoxState.hideRightBoxFlag
        ? 'contract-wrapper hide-contract-wrapper-width'
        : 'contract-wrapper show-contract-wrapper-width',
    ]">
      <div class="previewBox" :style="{ height: 1200 + 'px', width: '100%' }" v-html="html"></div>
      <div class="button-wrapper">
        <el-button @click="goCollaborativeApproval">重新选择合同模板</el-button>
        <el-button @click="saveAndNext" color="#FF7B50" style="color: #fff">保存并下一步</el-button>
      </div>
    </div>

    <!--  右侧固定参数box    -->
    <div class="rightBox" :class="rightBoxState.hideRightBoxFlag ? 'hideRightWidth' : 'showRightWidth'">
      <div class="ctrlBtnBox" :class="rightBoxState.hideRightBoxFlag ? 'toLeftBtn' : 'toLeftBtn'"
        @click="doControlRight">
        <el-icon :size="20" v-if="!rightBoxState.hideRightBoxFlag">
          <ArrowRight />
        </el-icon>
        <el-icon :size="20" v-else>
          <ArrowLeft />
        </el-icon>
      </div>
      <div class="formHeadBox" :style="rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
        ? 'display:none'
        : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
          ? 'display:none'
          : ''
        ">
        固定参数设置
      </div>

      <component :is="whichComponent" ref="formRef" @selectedDom="selectedDom"></component>
    </div>
  </div>
</template>

<script setup>
import { ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import store from "@/store";

import { contractApi } from "@/api/assets";
import { contractApi as contractApi2 } from "@/api/coordination";
import { onMounted, reactive, ref, watch, shallowRef } from "vue";
import { localSet } from "@/common/utils/GlobalUtils";
import { useRouter } from "vue-router";
import Template1 from "../template1/step1.vue";
import TemplateWuYe from "../templateWuYe/step1.vue";
import TemplateYiZhan from "../templateYiZhan/step1.vue";
const html = ref("");

let whichComponent = shallowRef(null);

const getTemplateTy = (i) => {
  //btnStatekey.value = i;
  switch (contractTemplateId) {
    case "1":
    case "2":
    case "3":
    case "4":
      whichComponent.value = Template1;
      break;
    case "5":
      whichComponent.value = TemplateWuYe;
      break;
    case "6":
      whichComponent.value = TemplateYiZhan;
      break;
    default:
      break;
  }
};

const router = useRouter();

// 从路由path中获取的
const getTemplateUrlKey = router.currentRoute.value.params.templateUrlKey;
const initInfo = () => {
  //console.log(router.currentRoute.value.params);
  getTemplateTy();
  contractApi.contractPreview(getTemplateUrlKey).then((res) => {
    if (!res.code) {
      html.value = res;
      /*  setTimeout(()=>{
          deleteDomText();
      },500)*/
      setTimeout(() => {
        createDomNodes();
      }, 1000);
    }
  });
};

// form相关
const formRef = ref(null);

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false, // 控制右侧内容部分
});
// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag;
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true;
    }, 200);
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false;
    }, 200);
  }
};

// 跳转--->新租表单列表
const goCollaborativeApproval = () => {
  router.push({ path: "/asset/collaborativeApproval/createXinZhuForm/index" });
};

//保存并下一步
const contractTemplateId = router.currentRoute.value.params.contractTemplateId;
const emits = defineEmits(["nextStep"]);
const saveAndNext = async () => {
  // 填充合同内容---> 保存
  let obj = {
    templateUrlKey: getTemplateUrlKey,
    param: JSON.parse(JSON.stringify(formRef.value.form)),
  };
  if (obj.param.fileOne && obj.param.fileOne !== null && obj.param.fileOne !== "") {
    obj.param.fileOne = obj.param.fileOne.fileAddress;
  }
  if (obj.param.fileTwo && obj.param.fileTwo !== null && obj.param.fileTwo !== "") {
    obj.param.fileTwo = obj.param.fileTwo.fileAddress;
  }
  if (obj.param.fileThree && obj.param.fileThree !== null && obj.param.fileThree !== "") {
    obj.param.fileThree = obj.param.fileThree.fileAddress;
  }
  obj.param.contractTemplateId = contractTemplateId;
  try {
    const valRes = await formRef.value.formValidate();
    console.log(valRes);

    if (valRes.valid === true) {
      console.log("contractTemplateId",contractTemplateId);
      if (contractTemplateId == '6') {
        contractApi2.bindData2(obj).then((res) => {
          if (res.code == 200) {
            store.commit("SET_XIN_ZU_FORM_YIZHAN", valRes.form);
            localSet("contractId", res.data);
            emits("nextStep", "GoEdit");
          }
        });
      } else {
        contractApi2.bindData(obj).then((res) => {
          if (res.code == 200) {
            switch (contractTemplateId) {
              case '6':
                store.commit("SET_XIN_ZU_FORM_YIZHAN", valRes.form);
                break;
              case "5":
                store.commit("SET_XIN_ZU_FORM_WUYE", valRes.form);
                break;
              default:
                store.commit("SET_XIN_ZU_FORM", valRes.form);
                break;
            }
            localSet("contractId", res.data);
            emits("nextStep", "GoEdit");
          }
        });
      }

    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * 给dom添加class属性
 * @param el
 * @param className
 */
const addClass = (el, className) => {
  let oldClassStr = "";
  //先判断元素中是否有class属性
  if (el.getAttribute("class")) {
    //获取原有的类名
    oldClassStr = el.getAttribute("class");
    //把原来的类名分割后添加入数组,判断要添加的类名是否已存在
    let oldClassArr = oldClassStr.split(" ");
    // 如果!=-1,说明存在或同名,不添加直接return
    if (oldClassArr.indexOf(className) !== -1) {
      console.log(className + "已经存在或同名");
      return;
    } else {
      //添加空格
      oldClassStr += " ";
    }
  }
  //添加新类名
  oldClassStr += className;
  el.setAttribute("class", oldClassStr);
};

/**
 * 创建dom节点
 */
const createDomNodes = () => {
  let previewBox = document.querySelector(".previewBox");
  let spanList = previewBox.getElementsByTagName("span");
  for (let span of spanList) {
    addClass(span, "fontStyle");
    for (let key in formRef.value.form) {
      if (span.innerText === "{{contactPhone}}") {
        addClass(span, "contactPhones");
      }
      let reg = new RegExp(key, "g");
      if (span.innerText.match(reg)) {
        if (key === "customerName" || key === "contactName") {
          // 承租方(乙方) leaseCustomers  contactName:联系人
          addClass(span, "leaseCustomers");
        } else {
          addClass(span, key);
        }
      }
    }
  }
};

/**
 * 选中dom 赋值,高亮
 */
const selectedDom = (className) => {
  let doms = document.querySelectorAll("." + className);
  let dom = doms.length === 0 ? {} : doms[0];
  if (doms.length === 0) {
    return;
  }

  let domList = document.querySelectorAll(".fontStyle");
  for (let item of domList) {
    item.style.background = "";
    item.style.fontWeight = 300;
    item.style.color = "#000000";
  }
  dom.style.background = "yellow";
  dom.style.fontWeight = 600;
  dom.style.color = "red";
  dom.scrollIntoView({ behavior: "smooth", block: "center" });
};

onMounted(() => {
  initInfo();
});
</script>

<style lang="scss" scoped>
.fillInTheContract-container {
  display: flex;
  justify-content: space-between;
  padding-bottom: 20px;

  .hide-contract-wrapper-width {
    width: 100% !important;
    transition: all 0.6s;
  }

  .show-contract-wrapper-width {
    width: calc(100% - 450px) !important;
    transition: all 0.6s;
  }

  .contract-wrapper {
    display: flex;
    flex-direction: column;

    .previewBox {
      border: 1px solid #e3e7f1;
      border-radius: 10px;
      padding: 36px 120px 30px;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .button-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 30px;
    }
  }

  .rightBox {
    border-left: 5px solid $title-sm-color;
    border-radius: 10px;
    padding: 30px 20px 30px 30px;
    position: relative;
    height: 1200px;
    overflow-y: auto;

    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 21px;

        .el-form-item__content {
          .selectStyle {
            width: 100%;

            .select-trigger {
              .el-input__wrapper {
                box-shadow: 0 0 0 1px $input-focus-bd-color inset;
              }
            }
          }

          .inputStyle {
            width: 100%;

            .el-input__wrapper {
              background-color: #fff8f6;
              box-shadow: 0 0 0 1px $input-focus-bd-color inset;

              .el-input__inner {
                text-align: center;
              }
            }
          }

          .inputCursor {
            .el-input__wrapper {
              .el-input__inner {
                cursor: pointer;
              }
            }
          }
        }
      }

      .modeItemBox {
        .el-form-item__content {
          .el-form-item {
            margin-bottom: 0;

            .el-form-item__content {
              .el-input {
                width: 54px;
                margin: 0 5px;
              }
            }
          }
        }
      }

      .limitInput {
        .el-form-item__content {
          display: flex;

          .dateRangeBox {
            margin-right: 6px;
            box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          }

          .dateInputBox {
            flex: 1;

            .el-input__wrapper {
              box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            }
          }

          .el-input {
            width: 100px;
          }
        }
      }

      .el-input {
        height: 40px;
      }
    }

    .ctrlBtnBox {
      width: 34px;
      height: 86px;
      line-height: 94px;
      text-align: center;
      padding-left: 10px;
      background: url("@/assets/iconImg/arrowbox.png") no-repeat;
      background-size: cover;
      position: absolute;
      top: 290px;
      cursor: pointer;
    }

    .toRightBtn {
      left: -39px;
    }

    .toLeftBtn {
      left: 14px;
    }

    .formHeadBox {
      font-size: 16px;
      font-family: SourceHanSansMedium;
      font-weight: 500;
      color: #1a1a1a;
      margin-bottom: 26px;
    }
  }

  .rightBox {
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 21px;

        .el-form-item__content {
          .selectStyle {
            width: 100%;
            // .select-trigger {
            //   .el-input__wrapper {
            //     box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            //   }
            // }
          }

          .inputStyle {
            width: 100%;

            .el-input__wrapper {
              background-color: #fff8f6;

              //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
              .el-input__inner {
                text-align: center;
              }
            }
          }

          .inputCursor {
            .el-input__wrapper {
              .el-input__inner {
                cursor: pointer;
              }
            }
          }
        }
      }

      /*      .modeItemBox {
        .el-form-item__content {
          .el-form-item {
            margin-bottom: 0;
            .el-form-item__content {
              .el-input {
                width: 54px;
                margin: 0 10px;
              }
            }
          }
        }
      }*/
      .limitInput {
        .el-form-item__content {
          display: flex;

          .dateRangeBox {
            margin-right: 6px;
            //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          }

          .dateInputBox {
            flex: 1;

            .el-input__wrapper {
              width: 100%;
              //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            }
          }

          .el-input {
            width: 100px;
          }
        }
      }
    }

    .housesListBox {
      .housesItemStyle {
        position: relative;

        .el-form-item__content {
          display: flex;

          .deletBtn {
            position: absolute;
            z-index: 1;
            left: -71px;
            cursor: pointer;
          }

          .el-input {
            flex: 1;

            &:nth-child(2) {
              margin-right: 10px;
            }
          }
        }
      }
    }
  }

  .showRightWidth {
    //width: 428px;
    width: 500px;
    transition: all 0.6s;
  }

  .hideRightWidth {
    width: 0px;
    padding-left: 0;
    border-left: none;
    transition: all 0.6s;
  }
}
</style>
